from insert_title_to_content import process_file
import os
import argparse

parser = argparse.ArgumentParser(description='插入标题到内容中')
parser.add_argument('directory', type=str, help='文件夹路径')

processed_dir_name = "加标题后结果"


def list_files(directory):
    # 获取指定文件夹下的所有文件和文件夹
    file_list = os.listdir(directory)
    return_list = []

    # 遍历文件夹中的每个文件和文件夹
    for file in file_list:
        # 获取文件或文件夹的完整路径
        path = os.path.join(directory, file)

        # 检查是否为文件
        if os.path.isfile(path) and path.endswith('.txt'):
            return_list.append(path)
        elif os.path.isdir(path):
            # 如果是文件夹，则递归调用list_files函数
            # list_files(path)
            pass
    return return_list


def read_content(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        # print(file_path)
        return f.read()



def process(file_path):
    result_path = os.path.join(file_path, processed_dir_name)
    if not os.path.exists(result_path):
        os.mkdir(result_path)
    file_path_list = list_files(file_path)
    success_processed_count = 0
    for file_path in file_path_list:
        file_name = os.path.basename(file_path)
        title = file_name.strip(".txt")
        content = read_content(file_path)
        final_content = process_file(title, content)
        final_file_path = os.path.join(result_path, file_name)
        with open(final_file_path, 'w', encoding='utf-8') as f:
            f.write(final_content)
        success_processed_count += 1
    print("成功处理了：{}篇内容".format(success_processed_count))


if __name__ == '__main__':
    # args = parser.parse_args()
    # process(args.directory)
    process("/Users/xujie/Downloads/排版结果(已排版)")